<?php		



class RbacApi extends ApiBase{


	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
	}
	
	public function getSiteRole($scode){
		return n_api("mysql")->cname('weixin')->select("select a.id as rmid,isdel,b.* from rbac_role_main as a
													left join rbac_role as b on a.role_id=b.id
													where a.scode='{$scode}' order by b.id");
	}
	/**
	 * 获取网站角色的用户PPID
	 */
	public function getSiteRolePpid($scode,$role){
		return array_keys(n_api("mysql")->cname('weixin')->selectIndex("select ppid from rbac_main as a
													left join rbac_role_main as b on a.rmid=b.id
													where b.scode='{$scode}' and role_id={$role}",'ppid'));		
	}
	/**
	 * 获取网站的用户PPID
	 */
	public function getSitePpid($scode){
		return array_keys(n_api("mysql")->cname('weixin')->selectIndex("select ppid from rbac_main as a
													left join rbac_role_main as b on a.rmid=b.id
													where b.scode='{$scode}'",'ppid'));		
	}
	
	/**
	 * 检查某个用户是否具有某个插件的某个权限。权限验证为【或】
	 * 
	 * 某些情况需要获得多个权限，只需要一个就返回OK
	 */
	public function checkOr($ppid,$scode,$pevent,$acode){
		$mysql = n_api("mysql")->cname('weixin');
		
		//获取用户的权限ids
		$uPrivate = $mysql->select("select private_ids from rbac_main as a
											left join rbac_role_main as b on a.rmid=b.id
											where ppid={$ppid} and scode='{$scode}'");
		$privateArr = array();
		if(!empty($uPrivate)){
			foreach($uPrivate as $key=>$val){
				$privateArr = array_merge($privateArr,explode(',', $val['private_ids']));
			}
		}
		
		//获取需要验证的权限
		$acodeArr = explode(',',$acode);
		$acodeArrN = array();
		$acodeArrY = array();
		foreach ($acodeArr as $key => $val) {
			if('!'==substr($val,0,1)){
				$acodeArrN[] = substr($val,0,1);
			}else{
				$acodeArrY[] = $val;
			}
		}
		$sql = " and acode in('".implode("','", $acodeArrN).implode("','", $acodeArrY)."')";
		$privateIds = $mysql->selectIndex("select id,acode from rbac_private where pevent='{$pevent}'".$sql);
		//echo "select id,acode from rbac_private where pevent='{$pevent}'".$sql;
		/*
		print_r($privateArr);
		echo '++++';
		print_r($acodeArrN);
		print_r($acodeArrY);
		print_r($privateIds);
		echo "<br /><br /><br />";
		 */
		//使用trycache来处理流程，一旦命中某一个权限，那么抛出异常，说明命中权限。返回true
		try{
			foreach ($privateIds as $key => $val) {
				if(!empty($acodeArrN) && in_array($val['acode'],$acodeArrN) && !in_array($val['id'],$privateArr)){
					throw new PException("存在权限".$val['acode']);
				}
				
				if(!empty($acodeArrY) && in_array($val['acode'],$acodeArrY) && in_array($val['id'],$privateArr)){
					throw new PException("存在权限".$val['acode']);
				}
				
			}
			
		}catch(PException $e){
			//echo $e->getMessage().'=============';
			return true;
		}
		return false;
	}
	/**
	 * 检查某个用户是否具有某个插件的某个权限。权限验证为【并】
	 */
	public function checkAnd($ppid,$scode,$pevent,$acode){
		$mysql = n_api("mysql")->cname('weixin');
		
		//获取用户的权限ids
		$uPrivate = $mysql->select("select private_ids from rbac_main as a
											left join rbac_role_main as b on a.rmid=b.id
											where ppid={$ppid} and scode='{$scode}'");
		$privateArr = array();
		if(!empty($uPrivate)){
			foreach($uPrivate as $key=>$val){
				$privateArr = array_merge($privateArr,explode(',', $val['private_ids']));
			}
		}
		
		//获取需要验证的权限
		$acodeArr = explode(',',$acode);
		$acodeArrN = array();
		$acodeArrY = array();
		foreach ($acodeArr as $key => $val) {
			if('!'==substr($val,0,1)){
				$acodeArrN[] = substr($val,0,1);
			}else{
				$acodeArrY[] = $val;
			}
		}
		$sql = " and acode in('".implode("','", $acodeArrN).implode("','", $acodeArrY)."')";
		$privateIds = $mysql->selectIndex("select id,acode from rbac_private where pevent='{$pevent}'".$sql);
		//echo "select id,acode from rbac_private where pevent='{$pevent}'".$sql;
		/*
		print_r($privateArr);
		echo '++++';
		print_r($acodeArrN);
		print_r($acodeArrY);
		print_r($privateIds);
		echo "<br /><br /><br />";
		 */
		//使用trycache来处理流程，一旦命中某一个权限，那么抛出异常，说明命中权限。返回true
		try{
			foreach ($privateIds as $key => $val) {
				if(!empty($acodeArrN) && in_array($val['acode'],$acodeArrN) && in_array($val['id'],$privateArr)){
					throw new PException("存在权限".$val['acode']);
				}
				
				if(!empty($acodeArrY) && in_array($val['acode'],$acodeArrY) && !in_array($val['id'],$privateArr)){
					throw new PException("存在权限".$val['acode']);
				}
				
			}
			
		}catch(PException $e){
			//echo $e->getMessage().'=============';
			return false;
		}
		return true;
	}

	/**
	 * 判断某一个插件、某一个网站的权限。
	 */
	public function checkPeventOr($ppid,$scode,$pevent){
		$acode = implode(',',array_keys(n_api("mysql")->cname('weixin')->selectIndex("select * from rbac_private where pevent='{$pevent}'",'acode')));
		return $this->checkOr($ppid, $scode, $pevent, $acode);
	}
	
	/**
	 * 判断一个用户是否拥有一个网站的一个插件的所有权限
	 */
	public function checkPeventAnd($ppid,$scode,$pevent){
		$acode = implode(',',array_keys(n_api("mysql")->cname('weixin')->selectIndex("select * from rbac_private where pevent='{$pevent}'",'acode')));
		return $this->checkAnd($ppid, $scode, $pevent, $acode);		
	}
	
	
	public function join($ppid,$rmid){
		
		$mysql = n_api("mysql")->cname('weixin');
		
		$sql = "select * from rbac_main where ppid={$ppid} and rmid={$rmid}";
		$main = $mysql->fetchFirst($sql);
		
		if(!empty($main)){
			return $main['id'];
		}				
		return $mysql->insert("rbac_main",array("ppid"=>$ppid,"rmid"=>$rmid,"ctime"=>time()));

				
	}
	
	/**
	 * 获取全部权限
	 */
	public function getPrivateAll(){
		return n_api("mysql")->cname('weixin')->selectIndex("select * from rbac_private");
	}
	/**
	 * 获取非站点权限
	 * 不直接读库的原因是以后可以加入缓存
	 */
	public function getTop(){
		$plist = $this->getPrivateAll();
		$rs = array();
		foreach($plist as $key=>$val){
			if('N'==$val['issite']){
				$rs[$val['id']] = $val;
			}
		}
		return $rs;
	}
	
	
	/**
	 * 
	 */
	public function getUserPrivate($ppid){

		$mysql = n_api("mysql")->cname('weixin');
		$plist = $this->getPrivateAll();
		
		
		//获取网站权限
		$rs['nsite'] = array();
		$main = $mysql->select("select ext_private,scode,private_ids from rbac_main as a
										left join rbac_role_main as b on a.rmid=b.id
										where ppid={$ppid}");
		if(!empty($main)){
			foreach($main as $key=>$val){
				$roleP = empty($val['private_ids'])?array():explode(',',$val['private_ids']);
				if(!empty($roleP)){
					foreach($roleP as $key1=>$val1){
						
						$rs['nsite'][$val['scode']][$val1] = $plist[$val1]['pevent'].'-'.$plist[$val1]['acode'];
					}
				}
				$extP = empty($val['ext_private'])?array():explode(',',$val['ext_private']);
				if(!empty($extP)){
					foreach($extP as $key1=>$val1){
						$rs['nsite'][$val['scode']][$val1] = $plist[$val1]['pevent'].'-'.$plist[$val1]['acode'];
					}
				}
			}
		}

		//获取全站权限
		$rs['top'] = array();
		$up = $mysql->fetchFirst("select * from rbac_user_main where ppid={$ppid}");
		if(!empty($up)){
			$tp = empty($up['private_ids'])?array():explode(',',$up['private_ids']);
			if(!empty($tp)){
			foreach($tp as $key=>$val){
				$rs['top'][$val] = $plist[$val]['pevent'].'-'.$plist[$val]['acode'];
			}				
			}
		}
		if(1==$ppid){
			$rs['top'][0] = 'rbac-root';
		}
		return $rs;
	}
	
	public function check($private,$scode=''){
		$a = empty($scode)?$_SESSION['private']['top']:$_SESSION['private']['nsite'][$scode];

		if(in_array($private,$a)){
			return TRUE;
		}
		return FALSE;
	}
}

